<template>
    <el-dialog v-model="show" :modal-class="{ 'open-account': current === 1, 'bind': current === 2 }"
        :width="current === 1 ? 580 : 500" align-center :show-close="false" class='open-account' :center="current === 2"
        destroy-on-close>
        <custom-title title="支付开户" v-if="current === 1" />
        <div class="setp">
            <template v-for="item, index in setpList" :key="item.value">
                <div class="setp-item">
                    <div :class="{ 'setp-num': true, active: current == item.value, finish: current > item.value }">
                        {{ item.value < current ? '' : item.value }}<el-icon v-if="item.value < current">
                            <Select /></el-icon>
                    </div>
                    {{ item.title }}
                </div>
                <div class="setp-line" v-if="index != setpList.length - 1"></div>
            </template>
        </div>
        <div class="content" v-if="current === 1">
            <el-form label-position="top">
                <el-form-item label="开户类型">
                    <el-radio-group v-model="registerType" @change="changeRegisterType">
                        <template v-for="item, index in memberType">
                            <el-radio v-if="registerType == index || !disabledType" :value="Number(index)">{{ item
                                }}</el-radio>
                        </template>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <component :is="components[registerType]" ref="formRef" v-model="form">
            </component>
        </div>
        <div class="content" v-if="current === 2">
            <BindBank ref="formRef" v-model="bindForm" :sendCodeStatus="sendCodeStatus"
                :currentAccountData="currentAccountData" :allowBind="allowBind" @sendCode="sendBindCode" />
        </div>
        <div class="content" v-if="current === 3">
            <Signing v-model="signForm" ref="formRef" :sendCodeStatus="sendCodeStatus"
                :currentAccountData="currentAccountData" @sendCode="sendSign" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="show = false">取消</el-button>
                <el-button type="primary" :disabled="current == 3 && !allowSign" @click="comfirm">
                    {{ okText }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { registerIndividual, registerOrganization, getMemberDetails, registerIndividualBusiness } from "@/apis/purse/member";
import { addBankCard, confirmAddBankCard, withdrawSign } from "@/apis/purse";
import { payConfig, tenantParams } from "@/utils/config";
import Individual from "./components/Individual.vue";
import SelfEmployed from "./components/SelfEmployed.vue";
import Enterprise from "./components/Enterprise.vue";
import BindBank from '../BindBank'
import Signing from "./components/Signing.vue";
import { ElMessage } from "element-plus";
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: true
    },
    currentAccountData: {
        type: Object,
        default: () => { }
    },
    step: {
        type: Number,
        default: 1
    },
    retry: {
        type: Boolean,
        default: false
    }
});

const memberType = {
    1: '个人',
    2: '企业',
    3: '个体工商户'
}
const components = {
    1: Individual,
    2: Enterprise,
    3: SelfEmployed
}
const registerType = ref(1); // 开户类型
const formRef = ref();
const bindForm = ref({
    accountType: props.currentAccountData.memberType == 2 ? 'ENTERPRISE' : 'INDIVIDUAL',
    cardType: 'DEBIT_CARD'
});
const signForm = ref({
})
const form = ref({})
const changeRegisterType = () => {
    clearTimer();
    nextTick(() => {
        formRef.value.resetFields();
        form.value = {};
    })
}
const setpList = [
    {
        title: '基本信息注册',
        value: 1
    },
    {
        title: '绑定银行卡',
        value: 2
    },
    {
        title: '完成签约',
        value: 3
    }
];
/**
 * 验证码当前状态
 */
const sendCodeStatus = ref({
    status: false,
    time: 60,
    timer: null
})
/**
 * 重置倒计时
 */
const clearTimer = () => {
    sendCodeStatus.value.status = false;
    clearInterval(sendCodeStatus.value.timer);
    sendCodeStatus.value.time = 60;
}
/**
 * 发送验证码之后的回调
 */
const sendCodeCallback = () => {
    sendCodeStatus.value.status = true;
    sendCodeStatus.value.timer = setInterval(() => {
        sendCodeStatus.value.time--;
        if (sendCodeStatus.value.time <= 0) {
            clearTimer()
        }
    }, 1000)
}
const registerBankInfo = ref({});
const allowBind = ref(false)
/**
 * 发送绑定银行卡短信or打款
 */
const sendBindCode = async () => {
    try {
        const params = {
            ...bindForm.value,
            walletId: props.currentAccountData.walletId,
            ...payConfig,
            memberId: props.currentAccountData.memberId
        }
        const res = await addBankCard(params);
        registerBankInfo.value = res.data;
        allowBind.value = true;
        sendCodeCallback();
    } catch (error) {
        console.log(error);
    }
}
const comfirmBindBank = async () => {
    let confingParams = {
        ...registerBankInfo.value,
        walletId: props.currentAccountData.walletId,
        memberId: props.currentAccountData.memberId,
        ...payConfig,
    }
    if (bindForm.value.accountType == 'INDIVIDUAL') {
        confingParams.verifyCode = bindForm.value.verifyCode;
    } else {
        confingParams.amount = bindForm.value.amount;
    }
    try {
        await confirmAddBankCard(confingParams);
        clearTimer();
        current.value = 3;
    } catch (error) {
        return;
    }
}
const okText = computed(() => {
    let result = ''
    switch (current.value) {
        case 1:
        case 2:
            result = '下一步'
            break;
        case 3:
            result = '完成'
            break;
        default:
            break;
    }
    return result;
})
const emit = defineEmits(['update:modelValue', 'flushed', 'openSure', 'update:retry']);
const show = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})
/**
 * 校验表单
 */
const validateForms = async () => {
    let result = false;
    switch (current.value) {
        case 1:
        case 2:
        case 3:
            result = await formRef.value.validate();
            break;
        default:
            break;
    }

    return result;
}

/**
 * 注册个人
 */
const enrollIndividual = async () => {
    const params = {
        ...form.value,
        ...payConfig,
        ...tenantParams,
    }
    const res = await registerIndividual(params);
    memberId.value = res.data.memberId;
}
/**
 * 注册企业
 */
const enrollOrganization = async () => {
    const params = {
        ...form.value,
        ...payConfig,
        ...tenantParams,
    }
    const res = await registerOrganization(params);
    memberId.value = res.data.memberId;
}
/**
 * 注册个体工商户
 */
const enrollSelfEmployed = async () => {
    const params = {
        ...form.value,
        ...payConfig,
        ...tenantParams,
    }
    const res = await registerIndividualBusiness(params);
    memberId.value = res.data.memberId;
}
const memberId = ref('')
const register = async () => {
    // registered：是否已经映射
    // registerType：1：个人，2：企业 3:个体工商户
    try {
        switch (registerType.value) {
            case 1:
                await enrollIndividual()
                break;
            case 2:
                await enrollOrganization();
                break;
            case 3:
                await enrollSelfEmployed();
                break;
            default:
                break;
        }
        // 刷新左侧账户列表，默认选中当前新增的账户
        emit('flushed', (list) => {
            return list.filter(v => v.memberId == memberId.value)[0];
        });
        show.value = false;
    } catch (error) {
    }
}
const signUrl = ref('');
const allowSign = ref(false)
/**
 * 签约请求
 */
const sendSign = async () => {
    try {
        let params = {
            ...payConfig,
            memberId: props.currentAccountData.memberId,
        }
        if (props.currentAccountData.memberType == 2) {
            const operator = { ...signForm.value };
            delete operator.code;
            if (Object.keys(operator).length) params.operator = operator;
        }
        const res = await withdrawSign(params);
        sendCodeCallback();
        signUrl.value = res.data.signUrl;
        allowSign.value = true;
    } catch (error) {
        console.log(error);
    }
}
/**
 * 确认签约
 */
const comfirmSign = () => {
    if (!signUrl.value) {
        show.value = false;
        ElMessage.error('已签约');
        return;
    };
    window.open(`${signUrl.value}${signForm.value.code}`);
    show.value = false;
    emit('openSure')
}
/**
 * 确认按钮的回调
 */
const comfirm = async () => {
    if ((await validateForms())) {
        try {
            switch (current.value) {
                case 1:
                    register()
                    break;
                case 2:
                    comfirmBindBank();
                    break;
                case 3:
                    comfirmSign();
                    break;
                default:
                    break;
            }
        } catch (error) {
        }
    }
}
const current = computed({
    get: () => props.step,
    set(val) {
        emit('update:step', val)
    }
})
const detailKey = {
    1: 'individualMember',
    2: 'enterpriseMember',
    3: 'soleProprietorshipMember'
}
const getDetails = async () => {
    const res = await getMemberDetails({ walletId: props.currentAccountData.walletId });
    registerType.value = Number(props.currentAccountData.memberType);
    form.value = {
        ...res.data[detailKey[props.currentAccountData.memberType]],
        walletId: props.currentAccountData.walletId,
    };
}
const disabledType = ref(false)
onMounted(() => {
    if (!props.retry) return;
    // 接收到回填信息，并回填
    if (props.currentAccountData && props.currentAccountData.memberStatus == 2) {
        getDetails();
        disabledType.value = true;
    }
})
</script>

<style scoped lang="scss">
.setp {
    margin: 20px 0;
    @include mixin.flex-center(space-between, center);
    gap: 8px;

    >div {
        @include mixin.flex-align;
        gap: 8px;
    }

    .setp-num {
        @include mixin.flex-center(center, center);
        width: 28px;
        height: 28px;
        background: #F2F3F5;
        border-radius: 50%;
        color: #4E5969;

    }

    .active {
        background: $topic;
        color: white
    }

    .setp-line {
        flex: 1;
        height: 1px;
        border-bottom: 1px dashed #D8D8D8;
    }

    .finish {
        background: #E8F3FF;
        color: $topic;
    }
}


.content {
    max-height: 70vh;
    overflow-y: scroll;
    position: relative;
    padding-bottom: 50px;
    margin-bottom: 10px;

    &::-webkit-scrollbar {
        width: 4px;
    }

    .input-select {
        flex: 1;
        @include mixin.flex;
        gap: 6px;
    }
}


::v-deep(.space) {
    flex: 1;
    display: flex;
    gap: 10px;
}

.name {
    width: 200px;
    height: 60px;
    border: 1px solid #DCDFE6;
    text-align: center;
    line-height: 60px;
    margin: 32px auto;
}

.bind-iphone {
    background: #F5F7FA;
    padding: 20px 20px 0;
    box-sizing: border-box;
    overflow: hidden;

    .success {
        font-size: 12px;
        color: #3D3D3D;
        margin-bottom: 16px;
    }

    .green {
        color: #19CC15;
    }


    .error {
        color: #3D3D3D;

        span {
            color: #FF3333;
        }

        .desc {
            margin: 8px 0 20px;
            font-size: 12px;
            color: #86909C;
        }
    }
}

.liaison {
    background: #F5F7FA;
    font-size: 12px;
    flex: 1;
    line-height: 30px;
    padding: 10px;
    margin-top: 2px;

    >div {
        color: #86909C;
    }
}
</style>
<style lang="scss">
.open-account {
    padding: 20px !important;
    overflow: hidden;

    .el-dialog__footer {
        position: absolute;
        bottom: 0;
        box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
        padding: 20px;
        width: 100%;
        left: 0;
        background: white;
    }
}

.bind {
    .el-dialog__footer {
        box-shadow: none;
    }
}
</style>